<template>
  <div class="chat-page">
    <el-card class="chat-card">
      <template #header>
        <div class="card-header">
          <h2>实时聊天</h2>
          <div class="connection-status">
            <el-tag :type="isConnected ? 'success' : 'danger'">
              {{ isConnected ? '已连接' : '未连接' }}
            </el-tag>
          </div>
        </div>
      </template>
      
      <div class="chat-container">
        <div class="messages-container" ref="messagesContainer">
          <div v-if="messages.length === 0" class="empty-state">
            <el-empty description="暂无消息，开始聊天吧！" />
          </div>
          <div v-else>
            <div
              v-for="message in messages"
              :key="message.id"
              :class="['message-item', message.fromUser === currentUser ? 'message-own' : 'message-other']"
            >
              <div class="message-avatar">
                <el-avatar :size="32" :src="message.avatar || ''">
                  {{ message.fromUser?.charAt(0)?.toUpperCase() }}
                </el-avatar>
              </div>
              <div class="message-content">
                <div class="message-header">
                  <span class="message-username">{{ message.fromUser }}</span>
                  <span class="message-time">{{ formatTime(message.createdAt) }}</span>
                </div>
                <div class="message-text">{{ message.content }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="input-container">
          <el-input
            v-model="newMessage"
            placeholder="输入消息..."
            @keyup.enter="sendMessage"
            :disabled="!isConnected"
          >
            <template #append>
              <el-button
                type="primary"
                @click="sendMessage"
                :disabled="!newMessage.trim() || !isConnected"
              >
                发送
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

export default {
  name: 'Chat',
  setup() {
    const authStore = useAuthStore()
    const messagesContainer = ref(null)
    const messages = ref([])
    const newMessage = ref('')
    const isConnected = ref(false)
    const stompClient = ref(null)

    const currentUser = authStore.user?.username

    const connectWebSocket = () => {
      try {
        // 使用SockJS和STOMP
        const socket = new SockJS('http://localhost:8084/ws')
        stompClient.value = Stomp.over(socket)
        
        stompClient.value.connect({}, 
          (frame) => {
            isConnected.value = true
            ElMessage.success('WebSocket连接成功')
            
            // 订阅公共消息频道
            stompClient.value.subscribe('/topic/public', (message) => {
              const receivedMessage = JSON.parse(message.body)
              messages.value.push(receivedMessage)
              scrollToBottom()
            })
          },
          (error) => {
            isConnected.value = false
            ElMessage.error('WebSocket连接失败: ' + error)
          }
        )
      } catch (error) {
        ElMessage.error('WebSocket连接失败: ' + error.message)
      }
    }

    const sendMessage = () => {
      if (!newMessage.value.trim() || !isConnected.value) return

      const message = {
        fromUser: currentUser,
        content: newMessage.value,
        createdAt: new Date(),
        type: 'CHAT'
      }

      if (stompClient.value && stompClient.value.connected) {
        stompClient.value.send('/app/chat.sendMessage', {}, JSON.stringify(message))
        newMessage.value = ''
      } else {
        ElMessage.error('连接已断开，无法发送消息')
      }
    }

    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
        }
      })
    }

    const formatTime = (time) => {
      return new Date(time).toLocaleTimeString()
    }

    onMounted(() => {
      // 动态加载STOMP和SockJS库
      const loadScript = (src) => {
        return new Promise((resolve, reject) => {
          const script = document.createElement('script')
          script.src = src
          script.onload = resolve
          script.onerror = reject
          document.head.appendChild(script)
        })
      }

      Promise.all([
        loadScript('https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js'),
        loadScript('https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js')
      ]).then(() => {
        connectWebSocket()
      }).catch(() => {
        ElMessage.error('无法加载WebSocket库')
      })
    })

    onUnmounted(() => {
      if (stompClient.value) {
        stompClient.value.disconnect()
      }
    })

    return {
      messagesContainer,
      messages,
      newMessage,
      isConnected,
      currentUser,
      sendMessage,
      formatTime
    }
  }
}
</script>

<style scoped>
.chat-page {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.chat-card {
  height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
}

.connection-status {
  display: flex;
  align-items: center;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 500px;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 10px;
}

.message-item {
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
}

.message-own {
  flex-direction: row-reverse;
}

.message-other {
  flex-direction: row;
}

.message-avatar {
  margin: 0 10px;
}

.message-content {
  max-width: 70%;
}

.message-own .message-content {
  text-align: right;
}

.message-header {
  margin-bottom: 5px;
  font-size: 12px;
  color: #909399;
}

.message-username {
  font-weight: bold;
  margin-right: 10px;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.message-text {
  background: #f5f7fa;
  padding: 8px 12px;
  border-radius: 8px;
  word-wrap: break-word;
}

.message-own .message-text {
  background: #409eff;
  color: white;
}

.input-container {
  margin-top: auto;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style> 